const express = require('express');
const { exec } = require('child_process');
const router = express.Router();
const fs = require('fs');
const path = require('path');

const SECRET = '909689902';
const LOG_FILE = path.join(__dirname, '../logs', 'webhook.log');

function log(message) {
  const now = new Date();
  const timeStr = `${now.getFullYear()}.${String(now.getMonth() + 1).padStart(2, '0')}.${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
  fs.appendFileSync(LOG_FILE, `[${timeStr}] ${message}\n`);
}

router.post('/', (req, res) => {
  const token = req.headers['x-gitee-token'];
  if (token !== SECRET) {
    log(`❌ Secret 错误，拒绝访问，错误的密钥是${token}`);
    return res.status(403).send('Forbidden');
  }
  log('🔔 收到 webhook 请求，开始异步执行部署脚本');
  res.send('Webhook received, deploying...');

  // 异步执行部署脚本
  const deployScriptPath = path.join(__dirname, '../deploy.sh');
  exec(`sh ${deployScriptPath}`, (err, stdout, stderr) => {
    if (err) {
      log(`❌ 部署失败: ${err.message}`);
      return;
    }
    log(`✅ 部署成功:\n${stdout}`);
  });
});

module.exports = router;
